package cn.itcast.task;

import cn.itcast.pojo.AliPropertise;
import cn.itcast.service.EmpService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class OssCleanupTask {
    @Autowired
    private AliPropertise aliPropertise;
    @Autowired
    private EmpService empService;
    private static final String ACCESS_KEY_ID = "LTAI5tQNNmen9GrSQzTVjGS8";
    private static final String ACCESS_KEY_SECRET = "GGGaKwpZ63goh5mcBdn2E4ilPpqj8U";

    // 每天凌晨2点执行
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanup() {
        try {
            //1.获取数据库文件列表
            Set<String> dbFiles = empService.findAllEmpImage();
            //2.获取OSS文件列表
            Set<String> ossFiles = listOssFiles();
            //3.对比两个列表，获取需要删除的图片
            Set<String> filesToDelete = new HashSet<>(ossFiles);
            //调用集合的removeAll方法,移除与之同名的文件
            filesToDelete.removeAll(dbFiles);
            //4.删除图片
            deleteFilesFromOss(filesToDelete);
            // 5. 任务结束（记录日志）
            System.out.println("清理完成，删除文件数量: " + filesToDelete.size());
        } catch (Exception e) {
            System.err.println("文件清理任务失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     * 获取OSS文件列表
     */
    private Set<String> listOssFiles() {
        Set<String> fileKeys = new HashSet<>();
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(aliPropertise.getEndpoint(), ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 存储当前页的文件列表
            ObjectListing objectListing;
            // 下一页的标记，初始为null
            String nextMarker = null;

            do {
                // 分页获取文件列表（每次1000个）
                objectListing = ossClient.listObjects(aliPropertise.getBucketName(), nextMarker);
                // 获取当前页的所有文件摘要信息
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                // 遍历当前页的文件，将文件key添加到集合中
                for (OSSObjectSummary s : sums) {
                    fileKeys.add(s.getKey());
                }
                // 获取下一页的标记
                nextMarker = objectListing.getNextMarker();
                // 判断是否还有下一页
            } while (objectListing.isTruncated());

        } finally {
            ossClient.shutdown();
        }
        return fileKeys;
    }
    /**
     * 批量删除OSS文件
     */
    private void deleteFilesFromOss(Set<String> fileKeys) {
        if (fileKeys.isEmpty()) return;
        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(aliPropertise.getEndpoint(), ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            // 阿里云SDK每次最多删除1000个
            int BATCH_SIZE = 1000;
            // 将Set转换为数组便于分批处理
            String[] keys = fileKeys.toArray(new String[0]);
            for (int i = 0; i < keys.length; i += BATCH_SIZE) {
                int end = Math.min(i + BATCH_SIZE, keys.length);
                String[] batch = Arrays.copyOfRange(keys, i, end);
                //将batch转成list<String>
                List<String> batchList = Arrays.asList(batch);
                ossClient.deleteObjects(
                        new DeleteObjectsRequest(aliPropertise.getBucketName())
                                .withKeys(batchList)
                                .withQuiet(true)  // 安静模式（不返回删除结果）
                );
            }
        } finally {
            ossClient.shutdown();
        }
    }
}
